using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using SiteManager;
using System.Data.SqlClient;
using System.IO;

public partial class SearchResults_dentist : System.Web.UI.Page
{
    //Create an Object of Manager class
    Manager mgr = new Manager(true,"ConnectionString");
    protected localFunction lfunction = new localFunction();
    public string tDoctorsId = "";
    public string frompage = "";
    public string TravelDis = "";
    public int gridcount = 0;
    int pageNo = 1;
    public string StdDoctorsId = "";
    string FeaDoctorsId = "";


    protected void Page_Load(object sender, EventArgs e)
    {
        bool bFeaDocsFound = false;
        bool bStdFeaDoc = false;
        bool bPreDocsFound = false;
        bool bEnFeaDoc = false;

        try
        {
            pageNo = Convert.ToInt32(Request.QueryString["page"]);
            if (pageNo == 0)
                pageNo = 1;
        }
        catch
        {
            pageNo = 1;
        }
        if (!Page.IsPostBack)
        {

            // set images for left panel
            if (imgfindoc != null)
            {
                imgfindoc.ImageUrl = Session["strhttp"] + "images/why-join-heading.gif";
                Imgbot.ImageUrl = Session["strhttp"] + "images/cor-bot.gif";
                //  Imgbanner.ImageUrl = Session["strhttp"] + "images/banner01.gif";
            }

            bFeaDocsFound = (Session["sDoctorsId"] != null && Session["sDoctorsId"].ToString().Trim() != "");
            bStdFeaDoc = (Session["StdFeaDoctorsId"] != null && Session["StdFeaDoctorsId"].ToString().Trim() != "");
            bPreDocsFound= (Session["PreDoctorsId"] != null && Session["PreDoctorsId"].ToString().Trim() != "");
            bEnFeaDoc = (Session["EnFeaDoctorsId"] != null && Session["EnFeaDoctorsId"].ToString().Trim() != "");

       //     Response.Write("Session[Travel_Dis]: " + Session["Travel_Dis"]);
            if (Session["Travel_Dis"] != null && Session["Travel_Dis"].ToString().Trim() != "")
            {
                TravelDis = Session["Travel_Dis"].ToString();
            }

            if (bFeaDocsFound || bStdFeaDoc|| bPreDocsFound || bEnFeaDoc)
            {
                //string to store all the doctor id's
                tDoctorsId = Session["sDoctorsId"].ToString();
                StdDoctorsId = Session["StdFeaDoctorsId"].ToString();

                // check the parent page
                try
                {
                    frompage = Session["pageFromOrAction"].ToString();

                }
                catch
                {
                    //frompage = "advanced";  
                }

                if (frompage == "advanced")
                {
                    BindGrid();
                    BindGridStdFeaDoc();

                }
                else if (frompage == "connect") //When the page is redirect from doctorContent.aspx
                {
                    BindGrid();
                    BindGridStdFeaDoc();

                }
                else
                {
                    BindGrid();
                    BindGridStdFeaDoc();
                }
            }
            else
            {
                Response.Redirect("SearchDentist_adv.aspx");
            }
        }

    }
    public void BindGrid()
    {
        tDoctorsId = Session["sDoctorsId"].ToString();
        if (tDoctorsId.Length > 0)
        {
            try
            {

                DataSet ds = mgr.ExecuteQuery(returnSql(GetPageId(pageNo)), "tbl_drdet");

                if (ds.Tables[0].Rows.Count > 0)
                {
                    gridcount = ds.Tables[0].Rows.Count;
                    //ds.Tables[0].DefaultView.Sort = " rating desc"; -- K
                    grdSearch.DataSource = ds.Tables[0].DefaultView;
                    grdSearch.DataBind();

                    if (Session["Travel_Dis"].ToString() != "" && Session["Travel_Dis"] != null)  // to make distance column visibility true if search criteria includes Distance Search Functionality
                    {
                        grdSearch.Columns[4].Visible = true;
                    }
                    else
                    {
                        grdSearch.Columns[4].Visible = false;
                    }

                    lblMsg.Text = "";
                    lblMsg.ForeColor = System.Drawing.Color.Navy;
                    lblMsg.Font.Bold = true;
                    lblMsg.Font.Size = 11;

                }
                else
                {
                    lblMsg.Text = "No Records for the search criteria specified found!! Please try again";
                    lblMsg.ForeColor = System.Drawing.Color.Red;
                }
            }
            catch
            {
                //         Response.Write(ex.Message);
            }
        }
        else
        {

        }
    }
    public void BindGridStdFeaDoc()
    {

        
        FeaDoctorsId = Session["StdFeaDoctorsId"].ToString();
        if (FeaDoctorsId.Length > 0)
        {
            try
            {

                DataSet ds = mgr.ExecuteQuery(returnSql(FeaDoctorsId), "tbl_drdet");
                if (ds.Tables[0].Rows.Count > 0)
                {
                    ds.Tables[0].DefaultView.Sort = " rating desc";

                    StandardFeaDoc.DataSource = ds.Tables[0].DefaultView;
                    //if (pageNo > grd_top3.PageCount)
                    //    grd_StandardFeaDoc.PageIndex = 1;
                    //else
                    //    grd_StandardFeaDoc.PageIndex = pageNo;
                    StandardFeaDoc.DataBind();
                    lbl_FeaMsg.Text = "";
                    lbl_FeaMsg.ForeColor = System.Drawing.Color.Navy;
                    lbl_FeaMsg.Font.Bold = true;
                    lbl_FeaMsg.Font.Size = 11;
                    tbl_feat.Visible = true;

                }
                else
                {
                    tbl_feat.Visible = false;
                    lbl_FeaMsg.Text = "";
                    lbl_FeaMsg.ForeColor = System.Drawing.Color.Red;
                }
            }
            catch (Exception ex)
            {
                Response.Write(ex.Message);
            }
        }
        else
        {
            tbl_feat.Visible = false;
            lbl_FeaMsg.Text = "<span style='color: #330000'><b><u>Featured Links</u></b></span><br><br>No more Featured links";
            lbl_FeaMsg.ForeColor = System.Drawing.Color.Red;

        }

    }
    string returnSql(string ids)
    {
        //Response.Write(ids);
        Manager mgr = new Manager(true,"ConnectionString");
        string strSql = @"SELECT QU FROM DENTIST_FUNC_RATING()";

        SqlDataReader dr = mgr.ExecuteQuery(strSql);
        System.String orderClause = "";
        System.String AttachMiles = "";
        if (Session["Travel_Dis"].ToString() != "" && Session["Travel_Dis"].ToString() != null) //  to order the result first by Distance and then by rating Desc / to Calculate Miles
        {
            orderClause = "order by Distance ASC, Rating Desc";
            AttachMiles = " , (dbo.GetDistanceInMiles('" + Session["ZipCode"].ToString() + "','" + Session["City"].ToString() + "','" + Session["State"].ToString() + "',zipcodesearch)) as Distance";

        }
        else
        {
            orderClause = "order by Rating Desc";
            AttachMiles = ",'' as distance";
        }

        if (dr.Read())
        {
            strSql = @"select (" + dr[0].ToString()
               + @") as rating,d.id as id,fname + ' ' + mname + ' ' + lname as docname, address1 + '<br>' + city + ', ' + state as address,
             Sp.specialty + isnull(', ' + (select tbl_DentistSubSpecialty.specialty from tbl_DentistSubSpecialty where
			tbl_DentistSubSpecialty.specialty not in(Sp.specialty) and
			 tbl_DentistSubSpecialty.id=d.secondaryspecialityid),'') as speciality,
            isnull(dp.website,'')as website,isnull(dp.photo,'') as photo,d.gender" + AttachMiles +
            " from tbl_Dentists d "
            + " left outer join tbl_secondaryspeciality s on s.id=d.secondaryspecialityid "
            + " left outer join tbl_dntpremium dp on dp.dnt_id=d.id " 
            + " left outer join tbl_dentistspecialty sp on sp.id=D.specialityid "
             + " where  d.isdelete=0 and d.id in (" + ids + ") " + orderClause;


//            Response.Write(strSql);

            //a.d. code, will be implemented, if required

            //(dbo.GetDistanceInMiles('" + Session["Travel_Dis"].ToString() + "','" + Session["City"].ToString() 
            //+ @"',substring(d.ZipCode,1,5))) as Distance

        }

        return strSql;
    }
    private int GetRecCount(string csvStr)
    {
        return csvStr.Split(new char[] { ',' }).Length;
    }
    int getcPostion(int pageNo)
    {
        string did = Session["sDoctorsId"].ToString();
        int startNo = (pageNo - 1) * 10;
        int pos = 0;
        int pr = 0;
        for (int i = 0; i < startNo; i++)
        {
            pos = did.IndexOf(',', pr);
            pr = pos + 1;
            if (did.IndexOf(',', pr) == -1)
            {
                pos = did.Length;
                break;
            }
        }
        return pos;
    }
    void PageIndexChange()
    {


        BindGrid();



    }
    string GetPageId(int pageNo)
    {
        string did = Session["sDoctorsId"].ToString();

        int StartIndex = getcPostion(pageNo);
        int lastIndex = getcPostion(pageNo + 1);
        int totalRecs = GetRecCount(did);

        //Response.Write("<br>" + StartIndex);
        //Response.Write("<br>" + lastIndex);
        string ids = did.Substring(StartIndex, lastIndex - StartIndex);
        ids = ids.TrimEnd(',').TrimStart(',');
        int startingRec = 10 * (pageNo - 1) + 1;
        int endingRec = startingRec + (GetRecCount(ids) - 1);
        //Response.Write("<br>" + ids);
        litPaging.Text = "<table width='100%'><tr><td>Displaying " + startingRec + " to " + endingRec + " of " + totalRecs + "</td><td align='right'>";
        if (pageNo > 1)
            litPaging.Text += "<a href='SearchResults_dentist.aspx?page=" + (pageNo - 1) + "'>Previous</a>";
        if (pageNo < (totalRecs / 10) || (pageNo == (totalRecs / 10) && (totalRecs % 10) != 0))
            litPaging.Text += "&nbsp;&nbsp;&nbsp;<a href='SearchResults_dentist.aspx?page=" + (pageNo + 1) + "'>Next</a>";
        litPaging.Text += "</td></tr></table>";
        litPagingBelow.Text = litPaging.Text;
        return ids;
    }
    protected void btnBackToSearch_Click(object sender, EventArgs e)
    {
        string goToCode = "";
        //if (Request.QueryString["frompage"] != null && Request.QueryString["frompage"].ToString() == "")
        if (Session["pageFromOrAction"] != null && Session["pageFromOrAction"].ToString() != "")
        {
            //string tFrompage = Request.QueryString["frompage"].ToString().Trim();
            goToCode = Session["pageFromOrAction"].ToString();
            switch (goToCode)
            {
                case "home":
                case "simple":
                    Response.Redirect("Default.aspx");
                    break;
                case "connect":
                case "ratePeer":
                    Response.Redirect(Session["strHttps"] + "Dentist/DentistContent.aspx");
                    break;
                case "RateDoctors":
                    Response.Redirect(Session["strHttp"] + "patient/patient_rate.aspx?fromPage=RateDentists");
                    break;
                case "drMessage":
                    Response.Redirect(Session["strHttp"] + "boardsblogs/blogs.aspx");
                    break;
                case "advanced":
                    Response.Redirect(Session["strHttp"] + "SearchDentist_adv.aspx");
                    break;
                default:
                    Response.Redirect(Session["strHttp"] + "SearchDentist_adv.aspx");
                    break;
            }

        }
        else
            Response.Redirect(Session["strHttp"] + "SearchDentist_adv.aspx");
    }
    protected void grdSearch_RowCreated(object sender, GridViewRowEventArgs e)
    {
       

    }
    protected void grdSearch_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        double overallRate = 0.0;
        if (e.Row.RowType == DataControlRowType.DataRow)
        {

            // Control  C = LoadControl("includes/showRate.ascx");
            //includes_showRate rateCC = (includes_showRate)C;
            //Response.Write(grdSearch.DataKeys[e.Row.RowIndex].Value.ToString().Trim());
            //if (grdSearch.DataKeys[e.Row.RowIndex].Value.ToString().Trim() != "")
            {
                //  rateCC.rate = Convert.ToDecimal(grdSearch.DataKeys[e.Row.RowIndex].Value.ToString().Trim());
                //  rateCC.totalScore = 100;
            }
            //e.Row.Cells[4].Controls.Add(rateCC);

            //  e.Row.Cells[4].Text = grdSearch.DataKeys[e.Row.RowIndex].Value.ToString().Trim();
            overallRate = Convert.ToDouble(e.Row.Cells[5].Text);
            if (overallRate > 100)
                overallRate = 100;

            ///K: 12 oct 2006
            ///if the doctors are rated below 50 they should be labeled as 'Not Rated'
            float fRateLimit = Convert.ToSingle(ConfigurationManager.AppSettings["MinRatingLimit"].ToString());
            e.Row.Cells[5].Text = ((overallRate >= fRateLimit) ? Math.Round(overallRate, 2).ToString() : "Not Rated");
            e.Row.Cells[5].ForeColor = ((overallRate >= fRateLimit) ? System.Drawing.Color.Blue : System.Drawing.Color.Red);
            ///k: code ends

        }
        if (e.Row.RowType == DataControlRowType.Pager)
        {

        }

    }
    protected void grdSearch_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        grdSearch.PageIndex = e.NewPageIndex;
        BindGrid();


    }
    
}
